package com.sjb.cp.service.impl;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sjb.cp.exception.BusinessException;
import com.sjb.cp.exception.ErrorCode;
import com.sjb.cp.exception.ThrowUtils;
import com.sjb.cp.model.enums.SpaceRoleEnum;
import com.sjb.cp.model.po.Space;
import com.sjb.cp.model.po.SpaceUser;
import com.sjb.cp.model.po.User;
import com.sjb.cp.model.request.space.SpaceQueryRequest;
import com.sjb.cp.model.request.spaceuser.SpaceUserAddRequest;
import com.sjb.cp.model.request.spaceuser.SpaceUserQueryRequest;
import com.sjb.cp.model.vo.SpaceUserVo;
import com.sjb.cp.model.vo.UserVo;
import com.sjb.cp.service.SpaceService;
import com.sjb.cp.service.SpaceUserService;
import com.sjb.cp.mapper.SpaceUserMapper;
import com.sjb.cp.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
* @author dell
* @description 针对表【space_user(空间成员表)】的数据库操作Service实现
* @createDate 2025-02-14 10:30:52
*/
@Service
public class SpaceUserServiceImpl extends ServiceImpl<SpaceUserMapper, SpaceUser>
    implements SpaceUserService{

    @Resource
    private UserService userService;

    @Resource
    private SpaceService spaceService;

    @Override
    public long addSpaceUser(SpaceUserAddRequest spaceUserAddRequest) {
        ThrowUtils.throwIf(spaceUserAddRequest == null, ErrorCode.PARAMS_ERROR);

        SpaceUser spaceUser = new SpaceUser();
        validateSpaceUser(spaceUserAddRequest,true);
        BeanUtils.copyProperties(spaceUserAddRequest,spaceUser);
        this.save(spaceUser);
        return spaceUser.getId();
    }

    /**
     * 空间成员参数校验
     * @param spaceUserAddRequest
     * @param add
     */
    private  void validateSpaceUser(SpaceUserAddRequest spaceUserAddRequest,boolean add){
        Long spaceId = spaceUserAddRequest.getSpaceId();
        Long userId = spaceUserAddRequest.getUserId();
        String spaceRole = spaceUserAddRequest.getSpaceRole();

        if (add){
            // 添加
            User user = userService.getById(userId);
            ThrowUtils.throwIf(user == null, ErrorCode.NOT_FOUND_ERROR,"用户不存在");
            Space space = spaceService.getById(spaceId);
            ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR,"空间不存在");
        }
        // 校验空间角色
        SpaceRoleEnum enumByValue = SpaceRoleEnum.getEnumByValue(spaceRole);
        if (enumByValue == null){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR,"空间角色不存在");
        }
    }

    @Override
    public QueryWrapper<SpaceUser> getQueryWrapper(SpaceUserQueryRequest spaceQueryRequest) {
        QueryWrapper<SpaceUser> queryWrapper = new QueryWrapper<>();
        if (spaceQueryRequest == null) {
            return queryWrapper;
        }
        // 从对象中取值
        Long id = spaceQueryRequest.getId();
        String spaceRole = spaceQueryRequest.getSpaceRole();
        Long spaceId = spaceQueryRequest.getSpaceId();
        Long userId = spaceQueryRequest.getUserId();

        queryWrapper.eq(ObjUtil.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjUtil.isNotEmpty(userId), "userId", userId);
        queryWrapper.eq(StrUtil.isNotBlank(spaceRole), "spaceRole", spaceRole);
        queryWrapper.eq(ObjectUtil.isNotEmpty(spaceId), "spaceId", spaceId);

        return queryWrapper;
    }

    @Override
    public SpaceUserVo getSpaceUserVo(SpaceUser spaceUser, HttpServletRequest request) {
        SpaceUserVo spaceUserVo = SpaceUserVo.objToVo(spaceUser);
        // 关联查询的用户信息
        Long userId = spaceUser.getUserId();
        if (userId != null && userId != 0){
            User user = userService.getById(userId);
            UserVo userVo = userService.getUserVo(user);
            spaceUserVo.setUserVo(userVo);
        }
        // 关联查询到的空间信息
        Long spaceId = spaceUser.getSpaceId();
        if (spaceId != null && spaceId != 0){
            Space space = spaceService.getById(spaceId);
            spaceUserVo.setSpaceVO(space);
        }
        return spaceUserVo;
    }

    @Override
    public List<SpaceUserVo> getSpaceUserVoList(List<SpaceUser> spaceUserList) {
        // 判断输入列表是否为空
        if (CollectionUtils.isEmpty(spaceUserList)){
            return Collections.emptyList();
        }
        // 对象 转成 vo实体
        List<SpaceUserVo> spaceUserVos = spaceUserList.stream().map(SpaceUserVo::objToVo).collect(Collectors.toList());
        // 关联的userId信息
        List<Long> userIdS = spaceUserList.stream().map(SpaceUser::getUserId).collect(Collectors.toList());
        List<User> userList = userService.listByIds(userIdS);
        Map<Long, List<User>> userIdListMap = userList.stream().collect(Collectors.groupingBy(User::getId));
        // 关联的spaceId信息
        List<Long> spaceIdS = spaceUserList.stream().map(SpaceUser::getSpaceId).collect(Collectors.toList());
        List<Space> spaceList = spaceService.listByIds(spaceIdS);
        Map<Long, List<Space>> spaceIdListMap = spaceList.stream().collect(Collectors.groupingBy(Space::getId));
        // 填充视图响应信息
        spaceUserVos.forEach(spaceUserVo -> {
            Long spaceId = spaceUserVo.getSpaceId();
            Long userId = spaceUserVo.getUserId();
            User user = null;
            if (userIdListMap.containsKey(userId)){
                user = userIdListMap.get(userId).get(0);
            }
            spaceUserVo.setUserVo(userService.getUserVo(user));
            Space space = null;
            if (spaceIdListMap.containsKey(spaceId)){
                space = spaceIdListMap.get(spaceId).get(0);
            }
            spaceUserVo.setSpaceVO(space);
        });
        return spaceUserVos;
    }
}




